<template>
    <div class="general-add">
        <a-modal width="1300px" :visible="visible" title="优惠券详情" @cancel="closeModal" class="yuan-modal general-add-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <div class="progress-panel">
                    <div class="pro-list" :class="pageKey>idx&&'pro-finish'" v-for="(item,idx) in progressList">
                        <div class="pro-top">
                            <span class="pro-idx">0{{idx+1}}</span>
                            <span class="pro-title">{{item.title}}</span>
                        </div>
                        <div class="pro-bottom">
                            <i class="iconfont" v-show="pageKey>idx">&#xe63b;</i>
                            <i class="iconfont" v-show="pageKey<=idx">&#xe640;</i>
                            <span class="pro-line"></span>
                        </div>
                    </div>
                </div>
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :class="isShow?'disable-form':''" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel yuan-form-col5">
                        <div class="form-panel-box" v-if="pageKey===0">
                            <div class="form-title">基本信息</div>

                            <a-form-model-item class="yuan-form-item" label="活动类型" prop="phone">
                                <span class="yuan-form-input">满减券</span>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="优惠券类型" prop="phone">
                                <span class="yuan-form-input">商城券</span>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="优惠券名称" prop="name">
                                <a-input class="yuan-form-input" placeholder="优惠券名称" v-model="formData.name"></a-input>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="领取活动时间" prop="startTime">
                                <a-range-picker class="yuan-form-input" v-model="formData.defStartTime" @change="dateChange"
                                    :placeholder="['开始日期','结束日期']" :format="['YYYY-MM-DD','YYYY-MM-DD']" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="最低消费" prop="minAmount">
                                <a-input class="yuan-form-input" placeholder="请输入金额" v-model="formData.minAmount"
                                    style="width:100px"></a-input>
                                <span class="yuan-form-unit">元，优惠：</span>
                                <a-input class="yuan-form-input" placeholder="请输入金额" v-model="formData.discountAmount"
                                    style="width:100px"></a-input>
                                <span class="yuan-form-unit">元</span>
                                <div class="form-item-tips c-danger">0为无最低消费限制，最低消费金额不能小于优惠金额</div>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="券使用有效期" prop="validityType" style="margin-top:20px">
                                <a-radio-group v-model="formData.validityType">
                                    <a-radio :value="1">
                                        <span>固定时间 </span>
                                        <a-range-picker class="yuan-form-input" @change="validityDateChange"
                                            v-model="formData.defValidityDate" :placeholder="['开始日期','结束日期']"
                                            :format="['YYYY-MM-DD','YYYY-MM-DD']" v-show="formData.validityType===1" />
                                    </a-radio>
                                    <div class="form-item-tips c-danger">选择固定时间时，有效期开始时间不能早于活动领取的开始时间</div>
                                    <div style="margin-top:20px"></div>
                                    <a-radio :value="2">
                                        <!-- <span>领取后 </span>
                                        <a-input class="yuan-form-input" style="width:100px" placeholder="请输入天数"
                                            v-model="formData.validityDays"></a-input>
                                        <span class="yuan-form-unit">天生效，有效期</span> -->
                                        <span class="yuan-form-unit">有效期</span>
                                        <a-input class="yuan-form-input" style="width:100px" placeholder="请输入天数"
                                            v-model="formData.validityDays" v-show="formData.validityType===2"></a-input>
                                        <span class="yuan-form-unit" v-show="formData.validityType===2">天</span>
                                    </a-radio>
                                </a-radio-group>
                            </a-form-model-item>

                        </div>
                        <div class="form-panel-box" v-if="pageKey===1">
                            <div class="form-title">发放规则</div>

                            <a-form-model-item class="yuan-form-row" label="领取方式" prop="issueType">
                                <a-radio-group v-model="formData.issueType">
                                    <a-radio :value="1">
                                        <span>用户主动领取 </span>
                                        <template v-if="formData.issueType===1">
                                            <span class="yuan-form-unit">发放总数量：</span>
                                            <a-input class="yuan-form-input" style="width:100px" placeholder="请输入数量"
                                                v-model="formData.issueQuantity"></a-input>
                                            <span class="yuan-form-unit" style="margin-left:120px">领取限制：每人限领</span>
                                            <a-input class="yuan-form-input" style="width:100px" placeholder="请输入数量"
                                                v-model="formData.limitPerPerson"></a-input>
                                            <span class="yuan-form-unit">张</span>
                                        </template>

                                    </a-radio>
                                    <div style="margin-top:5px"></div>
                                    <a-radio :value="2">系统自动发放 </a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <!-- <a-form-model-item class="yuan-form-row" label="仅限新用户" prop="userType">
                                <a-radio-group v-model="formData.userType">
                                    <a-radio :value="1">是</a-radio>
                                    <a-radio :value="0">否</a-radio>
                                </a-radio-group>
                            </a-form-model-item> -->

                        </div>
                        <div class="form-panel-box" v-if="pageKey===2">
                            <div class="form-title">适用范围</div>

                            <a-form-model-item class="yuan-form-row" label="适用商品" prop="phone">
                                <a-radio-group v-model="formData.goodsLimitType">
                                    <a-radio :value="1">全部商品</a-radio>
                                    <a-radio :value="2">指定分类</a-radio>
                                    <a-radio :value="3">指定商品</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <ClassListVue ref="ClassListVue" v-show="formData.goodsLimitType===2"
                                :defaltData="formData.applicableCategories" />
                            <GoodsListVue ref="GoodsListVue" v-show="formData.goodsLimitType===3"
                                :defaltData="formData.applicableGoods" />

                            <a-form-model-item class="yuan-form-row" label="适用门店" prop="storeLimitType"
                                v-if="formData.goodsLimitType!==3">
                                <a-radio-group v-model="formData.storeLimitType">
                                    <a-radio :value="1">全部机构</a-radio>
                                    <a-radio :value="2">指定机构</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <AgencyListVue ref="AgencyListVue" v-show="formData.storeLimitType===2 && formData.goodsLimitType!==3"
                                :defaltData="formData.couponStores" />

                        </div>
                        <div class="form-panel-box" v-if="pageKey===3">
                            <div class="form-title">使用规则</div>
                            <a-form-model-item class="yuan-form-row" label="互斥条件" prop="ifElseCouponShare">
                                <a-radio-group v-model="formData.ifElseCouponShare">
                                    <a-radio :value="0">不与其他优惠共享</a-radio>
                                    <!-- <a-radio :value="1">其他优惠共享</a-radio> -->
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="可用时段" prop="availableDaysJson">
                                <a-checkbox-group style="max-width:800px" v-model="formData.availableDaysJson">
                                    <a-checkbox value="全天可用">全天可用</a-checkbox>
                                    <!-- <a-checkbox value="周一">周一</a-checkbox>
                                    <a-checkbox value="周二">周二</a-checkbox>
                                    <a-checkbox value="周三">周三</a-checkbox>
                                    <a-checkbox value="周四">周四</a-checkbox>
                                    <a-checkbox value="周五">周五</a-checkbox>
                                    <a-checkbox value="周六">周六</a-checkbox>
                                    <a-checkbox value="周天">周天</a-checkbox> -->
                                </a-checkbox-group>
                            </a-form-model-item>

                        </div>
                        <div class="form-panel-box" v-if="pageKey===4">
                            <div class="form-title">其他</div>
                            <a-form-model-item class="yuan-form-row c-danger-row" label="加盟机构营销比例" prop="storeCommissionRate">
                                <a-input class="yuan-form-input" placeholder="请输入比例"
                                    v-model="formData.storeCommissionRate"></a-input>
                                <span class="yuan-form-unit c-danger">%</span>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="允许积分兑换" prop="allowSharing">
                                <a-radio-group v-model="formData.allowSharing">
                                    <a-radio :value="1">是</a-radio>
                                    <a-radio :value="0">否</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="积分数量" prop="pointsRequired"
                                v-if="formData.allowSharing===1">
                                <a-input class="yuan-form-input" placeholder="请输入兑换所需积分"
                                    v-model="formData.pointsRequired"></a-input>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-row" label="使用说明" prop="usageDescription">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.usageDescription" placeholder="用户领取时可看" :maxLength="500" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="备注" prop="remarks">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.remarks" placeholder="优惠券备注，不对用户展示" :maxLength="500" />
                            </a-form-model-item>

                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <a-button @click="closeModal">
                    取消
                </a-button>
                <a-button type="primary" v-show="pageKey!==0" @click="()=>pageKey=pageKey-1">
                    上一步
                </a-button>
                <a-button type="primary" v-show="pageKey!==4" @click="clickNext">
                    下一步
                </a-button>
                <a-button @click="clickShow" type="primary" :loading="saveLoading" v-show="pageKey===4">
                    预览
                </a-button>

            </template>
        </a-modal>
        <DetailVue :visible="detailVisible" @closeModal="() => detailVisible = false" :editInfo="showData" :isPreview="true"
            @modalOk="modalOk" />
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import api from "@/api/api";
import AgencyListVue from "./generalDetailAgencyList.vue";
import GoodsListVue from "./generalDetailGoodsList.vue";
import ClassListVue from "./generalDetailClassList.vue";
import DetailVue from "./shopMallDetail.vue";
import marketApi from "@/api/marketApi";
import { toFen, toYuan } from "@/utils";
@Component({
    name: "tpl",
    components: { UploadVue, DetailVue, AgencyListVue, GoodsListVue, ClassListVue },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editInfo!: any;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            this.pageKey = 0;
            if (this.editInfo.id) {
                this.formData = {
                    ...this.editInfo,
                    defStartTime: [this.editInfo.startTime, this.editInfo.endTime],
                    defValidityDate: [this.editInfo.validityStartTime, this.editInfo.validityEndTime],
                    minAmount: toYuan(this.editInfo.minAmount),
                    discountAmount: toYuan(this.editInfo.discountAmount),
                };
            } else {
                this.formData = {};
            }
        } else {
        }
    }
    pageKey = 0;
    progressList = [
        { title: "基本信息" },
        { title: "发放规则" },
        { title: "适用范围" },
        { title: "使用规则" },
        { title: "其他" },
    ];

    saveLoading = false;
    formData: any = {
        phone: "",
        address: "",
        pictures: [],
    };
    rules = {
        name: [{ required: true, message: "请输入优惠券名称", trigger: "change" }],
        pageTable: [{ required: true, message: "请输入banner标题", trigger: "change" }],
        startTime: [{ required: true, message: "请选择活动时间", trigger: "change" }],
        minAmount: [{ required: true, message: "请输入最低消费金额", trigger: "change" }],
        validityType: [{ required: true, message: "请选择有效期类型", trigger: "change" }],
        issueType: [{ required: true, message: "请选择发放方式", trigger: "change" }],
        userType: [{ required: true, message: "请选择用户类型", trigger: "change" }],
        storeLimitType: [{ required: true, message: "请选择适用门店", trigger: "change" }],
        ifElseCouponShare: [{ required: true, message: "请选择是否与其他优惠共享", trigger: "change" }],
        availableDaysJson: [{ required: true, message: "请选择可用时段", trigger: "change" }],
        storeCommissionRate: [{ required: true, message: "请填写加盟机构营销比例", trigger: "change" }],
        allowSharing: [{ required: true, message: "请选择是否允许积分兑换", trigger: "change" }],
        pointsRequired: [{ required: true, message: "请填写兑换所需积分数量", trigger: "change" }],
        usageDescription: [{ required: true, message: "请填写说明", trigger: "change" }],
    };
    async mounted() {}

    closeModal() {
        this.$emit("closeModal");
    }
    validForm(callback, setp?) {
        if (!setp || setp === 1) {
            if (!this.formData.discountAmount) {
                this.$message.error("请输入优惠金额");
                return;
            }
            if (this.formData.validityType === 1 && !this.formData.validityStartTime) {
                this.$message.error("请选择有效期");
                return;
            }
            if (this.formData.validityType === 2 && !this.formData.validityDays) {
                this.$message.error("请填写有效期天数");
                return;
            }
        }
        if (!setp || setp === 2) {
            if (this.formData.issueType === 1 && !this.formData.issueQuantity) {
                this.$message.error("请填写发放总量");
                return;
            }
            if (this.formData.issueType === 1 && !this.formData.limitPerPerson) {
                this.$message.error("请填写每人限领数量");
                return;
            }
        }
        if (!setp || setp === 3) {
            //如果选择指定商品，清空机构信息
            if (this.formData.goodsLimitType === 3) {
                this.formData.storeLimitType = 1;
                this.formData.couponStores = [];
            }

            if (this.formData.storeLimitType === 2) {
                if (this.formData.couponStores.length === 0) {
                    this.$message.error("请选择适用门店");
                    return;
                }
                const find = this.formData.couponStores.find((item) => {
                    return item.usageLimit === "";
                });
                if (find) {
                    this.$message.error("请填写机构领取数量");
                    return;
                }
                if (this.formData.issueType === 1) {
                    let total = 0;
                    this.formData.couponStores.forEach((item) => {
                        total += Number(item.usageLimit) || 0;
                    });
                    if (total != Number(this.formData.issueQuantity)) {
                        this.$message.error(`各机构领取总数量必须等于发放总数量:${this.formData.issueQuantity}`);
                        return;
                    }
                }
            }
        }

        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            callback && callback();
        });
    }
    async modalOk() {
        this.detailVisible = false;
        this.validForm(async () => {
            this.saveLoading = true;
            try {
                const data = {
                    ...this.formData,
                    type: "商城券",
                    activityType: "满减券",
                    generateType: "PLATFORM",

                    minAmount: toFen(this.formData.minAmount),
                    discountAmount: toFen(this.formData.discountAmount),
                };

                const res = await marketApi.addOrUpdateCoupon(data);
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }

    dateChange(e: any[]) {
        const arr = e.map((item) => item.format("YYYY-MM-DD"));
        this.formData.startTime = arr[0];
        this.formData.endTime = arr[1];
    }
    validityDateChange(e: any[]) {
        const arr = e.map((item) => item.format("YYYY-MM-DD"));
        this.formData.validityStartTime = arr[0];
        this.formData.validityEndTime = arr[1];
    }
    clickNext() {
        const pageKey = this.pageKey + 1;
        if (this.pageKey === 2) {
            this.formData.couponStores = (this.$refs["AgencyListVue"] as any).getPageData();
            this.formData.applicableCategories = (this.$refs["ClassListVue"] as any).getPageData();
            this.formData.applicableGoods = (this.$refs["GoodsListVue"] as any).getPageData();
        }
        this.validForm(() => {
            this.pageKey = pageKey;
        }, pageKey);
    }
    detailVisible = false;
    showData = {};
    clickShow() {
        this.validForm(() => {
            this.showData = {
                ...this.formData,
                minAmount: toFen(this.formData.minAmount),
                discountAmount: toFen(this.formData.discountAmount),
            };
            this.detailVisible = true;
        });
    }
}
</script>
<style lang="scss">
.general-add-modal {
    .ant-modal-body {
        background-color: rgba(64, 158, 255, 0.1);
    }

    .progress-panel {
        display: flex;
        align-items: center;
        padding: 0 50px 10px 50px;
    }
    .pro-list {
        opacity: 0.5;
        margin-right: 10px;
    }
    .pro-list:last-child {
        .pro-line {
            display: none;
        }
    }
    .pro-idx {
        font-weight: 500;
        font-size: 30px;
        color: #222222;
    }
    .pro-title {
        font-size: 14px;
        color: #6d6d6d;
        margin-left: 5px;
    }
    .pro-bottom {
        display: flex;
        align-items: center;
        .iconfont {
            color: #4469f1;
            font-size: 32px;
            line-height: 40px;
        }
    }
    .pro-line {
        width: 150px;
        margin-left: 10px;
        height: 1px;
        border-bottom: solid 2px #4469f1;
    }
    .pro-finish {
        opacity: 1;
        .pro-line {
            border-bottom: dashed 2px #4469f1;
        }
    }

    .form-item-tips {
        font-size: 12px;
        line-height: 20px;
    }

    .c-danger-row .ant-form-item-label > label {
        color: #ff4949 !important;
    }
}
</style>
